package engine

import (
	"io"
	"net/http"
)

type HTTPForwarder struct {
	forwarder RequestForwarder
}

func NewHTTPForwarder(f RequestForwarder) *HTTPForwarder {
	return &HTTPForwarder{
		forwarder: f,
	}
}

func (h *HTTPForwarder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	defer func() {
		if r.Body != nil {
			r.Body.Close()
		}
	}()

	resp, err := h.forwarder.Forward(r)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadGateway)
		return
	}
	defer resp.Body.Close()

	// Copy headers
	for k, v := range resp.Header {
		w.Header()[k] = v
	}
	w.WriteHeader(resp.StatusCode)

	// Copy body
	if _, err := io.Copy(w, resp.Body); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
